package com.sparrow.support;

import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.sparrow.constant.CACHE_KEY;
import com.sparrow.constant.CONFIG;
import com.sparrow.core.Cache;
import com.sparrow.utils.Config;

public class ActionFilterSupport {
	// 供单例使用 成员变量全部为常量
	public final String AJAXCACHE = "ajaxCache";
	public final String RESULT = "result";
	public final String SOURCE = "source";
	public final String DIRECTION = "direction";
	public final String STOP = "stop";
	public final String DIRECTIONURL = "directionUrl";
	public final String SOURCEURL = "sourceUrl";
	public final String URLPARAMETERS = "urlParameters";
	public final String POLICY = "policty";

	public String getActionKey(HttpServletRequest reqeust) {
		Object oactionKey = reqeust
				.getAttribute("javax.servlet.include.servlet_path");
		String actionKey = null;
		if (oactionKey != null) {
			actionKey = oactionKey.toString();
		} else {
			actionKey = reqeust.getServletPath();
		}
		System.out.println(String.valueOf(Thread.currentThread().getId())
				+ "actionSupport:" + reqeust + "|" + actionKey);
		return actionKey;
	}

	public String getSystemLanguage() {
		return Config.getValueInCache(CONFIG.LANGUAGE);
	}

	public String getCurrentUserId(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		return Login.getUser(cookies);
	}

	public String getCurrentUserName(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		return Login.getUser(cookies, true);
	}

	public String getBasePath(HttpServletRequest request) {
		Object basePath = Config.getValueInCache(CONFIG.ROOT_PATH);
		if (basePath == null) {
			String serverName = request.getServerName();
			String path = request.getContextPath();
			basePath = request.getScheme()
					+ "://"
					+ request.getServerName()
					+ (request.getServerPort() == 80 ? "" : ":"
							+ request.getServerPort()) + path;
			// eclipse tomcat 启动时会默认请示http://localhost故此处加此判断
			if (!serverName.toLowerCase().equals("localhost")) {
				Cache.getInstance().put(CACHE_KEY.CONFIG_FILE,
						CONFIG.ROOT_PATH, basePath);
			}
		}
		return basePath.toString();
	}

	public String getClientIp(ServletRequest reqeust) {
		if (reqeust == null) {
			return "127.0.0.1";
		}
		HttpServletRequest httpRequest = (HttpServletRequest) reqeust;
		String ip = httpRequest.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = httpRequest.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = httpRequest.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = reqeust.getRemoteAddr();
		}
		return ip;
	}

}
